package com.dhj.expression;

import com.dhj.entity.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author DaHuaJia
 * @Description 自定义Spring Security 权限校验方法
 * @Date 2022-04-04 19:01:58
 */
@Component("dhj")
public class DhjExpressionRoot {

    /**
     * 自定义权限校验，只要是其子集即可认证通过。
     * 例：用户有sys:say权限，即可认证通过sys:say:hello
     */
    public boolean hasDhjAuthority(String authority) {
        if (!StringUtils.hasText(authority)) {
            return false;
        }
        // 获取当前用户的权限信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        List<String> permissions = loginUser.getPermissions();

        // 判断用户权限集合中是否存在authority
        for (String permission : permissions) {
            if (authority.indexOf(permission) != -1) {
                return true;
            }
        }
        return false;
    }

}
